<template>
  <view class="main">
    <u-loading-page :loading="loading" bgColor="(255, 255, 255)" loading-text="加载中"></u-loading-page>
    <view v-if="!loading">
      <!-- 标题 -->
      <view class="title">
        {{ editInfo.title }}
      </view>

      <!-- 头部用户信息 -->
      <view class="header">
        <view class="header-img">
          <image :src="editInfo.user_id[0].avatar_file.url"></image>
        </view>
        <view class="header-info">
          <view class="header-info-name">
            {{ editInfo.user_id[0].username }}
          </view>
          <view class="header-info-time">
            <uni-dateformat :date="editInfo.publish_date" :threshold="[60000, 360000 * 24 * 30]">
            </uni-dateformat>
            ·{{ editInfo.province.city }}
          </view>
        </view>
      </view>

      <!-- 内容 -->
      <view class="content">
        <u-parse :content="editInfo.content" :tagStyle="tagStyle"></u-parse>
      </view>

      <!-- 底部点赞信息 -->
      <view class="interaction">
        <!-- 点赞 -->
        <view class="interaction-praise flex" @click="likeUpdate">
          <view :style="{backgroundColor:editInfo.likeStatus ?  '#0199fe' :''}" class="interaction-praise-box flex">
            <text style="font-size: 1rem; color: #fff; margin-right: 10rpx" class="iconfont icon-zan"></text>
            <text style="font-size: 24rpx; color: #fff">{{
              editInfo.like_count
            }}</text>
          </view>
        </view>
        <!-- 点赞头像 -->
        <view class="interaction-image">
          <template v-for="item in avatarArr">
            <image :src="item"></image>
          </template>
        </view>
        <!-- 浏览人数 -->
        <view class="flex" style="margin-bottom: 40rpx; width: 100%">
          <text class="interaction-praise-num">{{ editInfo.view_count }}</text>
          <text style="font-size: 24rpx">人看过</text>
        </view>
      </view>
      <!-- 评论人 -->
      <view class="comment">
        <view style="padding-bottom:50rpx" v-if="!commentList.length && noComment">
          <u-empty mode="comment" icon="https://cdn.uviewui.com/uview/empty/comment.png">
          </u-empty>
        </view>

        <view class="content" v-if="commentList.length">
          <view class="item" v-for="item in commentList">
            <comment-item :item="item" @removeEnv="PremoveEnv"></comment-item>
          </view>
        </view>

      </view>

      <view>
        <comment-frame :commentObj='commentObj'  @commentEnv="PcommentEnv" :placeholder="placeholder"></comment-frame>
      </view>
    </view>
  </view>
</template>

<script>
import { updateLike } from "../../utils/tools";
import { store } from "../../uni_modules/uni-id-pages/common/store";
let { operation } = uniCloud.importObject("utilsObj", {
  customUI: true // 取消自动展示的交互提示界面
});
const db = uniCloud.database();

export default {
  data() {
    return {
      editId: "",
      editInfo: {},
      // 设置富文本样式
      tagStyle: {
        p: "color: #333;font-size:30rpx;margin-bottom:10rpx",
        img: "padding:20rpx 0"
      },
      loading: true,
      num: 0,
      avatarArr: [],
      commentObj: {
        article_id: "",
        comment_type: 0
      },
      placeholder: "请输入内容",
      commentList: [],
      noComment:true
    };
  },
  onLoad(e) {
    this.editId = e.id;
    this.commentObj.article_id = e.id;
    this.getEditIdData();
    this.readUpdate();
    this.getAvatares();
    this.getComment();
  },
  computed: {
    userInfo() {
      return store.userInfo;
    }
  },
  methods: {
    //删除评论的回调
			PremoveEnv(e){
				console.log(e);
				let index=this.commentList.findIndex(item=>{
					return item._id == e.id
				})
				this.commentList.splice(index,1)
			},
    //评论成功后的回调
			PcommentEnv(e){
				console.log(e);
				
				this.commentList.unshift({
					...this.commentObj,
					...e,
					user_id:[store.userInfo]
				})
			},
    //获取评论列表
    async getComment() {
      let commentTemp = db
        .collection("quanzi_comment")
        .where(`article_id == "${this.editId}" && comment_type==0`)
        .orderBy("comment_date desc")
        .limit(20)
        .getTemp();
      let userTemp = db
        .collection("uni-id-users")
        .field("_id,username,nickname,avatar_file")
        .getTemp();

      let res = await db.collection(commentTemp, userTemp).get();
      console.log(res)
      // return;

      let idArr=res.result.data.map(item=>{
      	return item._id
      })

      let replyArr=await db.collection("quanzi_comment").where({
      	reply_comment_id:db.command.in(idArr)
      }).groupBy('reply_comment_id')
      .groupField('count(*) as totalReply').get();

      res.result.data.forEach(item=>{
      	let index=replyArr.result.data.findIndex(find=>{
      		return find.reply_comment_id == item._id
      	})
      	if(index>-1) item.totalReply = replyArr.result.data[index].totalReply
      })

      if (res.result.data == 0) this.noComment = true;
      this.commentList = res.result.data;
    },
    // 获取点赞用户头像
    async getAvatares() {
      let likes = db
        .collection("quanzi_like")
        .where({
          article_id: this.editId
        })
        .getTemp();

      let avatars = db
        .collection("uni-id-users")
        .field("_id,avatar_file")
        .getTemp();

      let { result } = await db
        .collection(likes, avatars)
        .limit(5)
        .get();

      result.data.forEach(value => {
        this.avatarArr.push(value.user_id[0].avatar_file.url);
      });
    },
    // 更具文章id查看文章详情
    async getEditIdData() {
      if (this.num == 0) {
        this.loading = true;
        this.num++;
      }
      // 主表 article
      let editTemp = await db
        .collection("quanzi_article")
        .where({
          _id: this.editId
        })
        .getTemp();

      // 副表 user
      let userTemp = await db
        .collection("uni-id-users")
        .field("_id,username,nickname,avatar_file")
        .getTemp();

      // 副表 like
      let likeTemp = await db
        .collection("quanzi_like")
        .where(`article_id == '${this.editId}' && user_id == $cloudEnv_uid`)
        .getTemp();

      let likes = [editTemp, userTemp];

      if (store.hasLogin) likes.push(likeTemp);

      let { result } = await db.collection(...likes).get();

      let likeStatus = false;

      if (store.hasLogin)
        likeStatus = result.data[0]._id.quanzi_like.length ? true : false;

      result.data[0].likeStatus = likeStatus;

      this.editInfo = result.data[0];
      this.loading = false;
    },
    // 用户浏览详情页自增查看人数
    async readUpdate() {
      let result = await operation(
        "quanzi_article",
        "view_count",
        this.editId,
        1
      );
      // console.log(result);
    },
    // 进行节流
    likeUpdate() {
      uni.$u.throttle(this.like, 1000);
    },
    // 用户点赞
    async like() {
      if (store.hasLogin) {
        this.editInfo.likeStatus
          ? this.editInfo.like_count--
          : this.editInfo.like_count++;

        if (this.editInfo.likeStatus) {
          let index = this.avatarArr.indexOf(this.userInfo.avatar_file.url);
          this.avatarArr.splice(index, 1);
        } else {
          this.avatarArr.push(this.userInfo.avatar_file.url);
        }
        this.editInfo.likeStatus = !this.editInfo.likeStatus;
      }

      // 判断当前用户是否点赞
      updateLike(this.editId);
    }
  }
};
</script>

<style lang="scss" scoped>
.flex {
  display: flex;
  justify-content: center;
  align-items: center;
}

.main {
  background: #f8f8f8;
  height: calc(100vh - var(--window-top));

  .comment {
    padding: 30rpx;
    padding-bottom: 120rpx;
    .item {
      padding: 10rpx 0;
    }
  }

  .title {
    font-size: 36rpx;
    font-weight: bold;
    background-color: #fff;
    padding: 20rpx 20rpx;
  }

  .header {
    background-color: #fff;
    padding: 20rpx 20rpx;
    display: flex;

    .header-img {
      image {
        border-radius: 50%;
        width: 70rpx;
        height: 70rpx;
      }
    }

    .header-info {
      margin-left: 20rpx;
      display: flex;
      flex-direction: column;

      .header-info-time {
        font-size: 24rpx;
        color: #999;
        letter-spacing: 3rpx;
      }
    }
  }

  .content {
    background-color: #fff;
    padding: 0rpx 20rpx;
    text-indent: 2rem;
    letter-spacing: 3rpx;
  }
  

  .interaction {
    padding: 0rpx 20rpx 0rpx 20rpx;
    background-color: #fff;
    height: 300rpx;
    display: flex;
    flex-wrap: wrap;

    .interaction-praise {
      width: 100%;

      .interaction-praise-box {
        width: 200rpx;
        height: 100rpx;
        border-radius: 100rpx;
        background-color: rgba(163, 163, 163, 0.4);
      }
    }

    .interaction-image {
      text-align: center;
      width: 100%;

      image {
        border-radius: 50%;
        width: 70rpx;
        height: 70rpx;
      }
    }

    .interaction-praise-num {
      font-size: 24rpx;
      color: #0199fe;
      margin-right: 5rpx;
    }
  }
}
</style>
